package com.gpframework.module.module.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gpframework.common.config.GpframeworkConfig;
import com.gpframework.common.constant.BrandConstants;
import com.gpframework.common.constant.CacheConstants;
import com.gpframework.common.constant.WeiXinConstants;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.domain.entity.SysUser;
import com.gpframework.common.core.redis.RedisCache;
import com.gpframework.common.enums.ResourcesBusiness;
import com.gpframework.common.exception.BaseException;
import com.gpframework.common.exception.DataNotFoundException;
import com.gpframework.common.utils.MessageUtils;
import com.gpframework.common.utils.file.FileUploadUtils;
import com.gpframework.module.base.domain.req.BaseReq;
import com.gpframework.module.common.domain.CommonResource;
import com.gpframework.module.common.domain.CommonWxUser;
import com.gpframework.module.common.domain.req.CommonResourceReq;
import com.gpframework.module.common.domain.req.CommonWxAppletInfoReq;
import com.gpframework.module.common.domain.vo.*;
import com.gpframework.module.common.mapper.CommonWxUserMapper;
import com.gpframework.module.common.service.ICommonResourceService;
import com.gpframework.module.common.service.ICommonWxAppletInfoService;
import com.gpframework.module.module.domain.BrandAuditRecord;
import com.gpframework.module.module.domain.BrandInfo;
import com.gpframework.module.module.domain.req.BrandInfoUpdate;
import com.gpframework.module.module.domain.req.BrandStoreReq;
import com.gpframework.module.module.domain.vo.BrandInfoVo;
import com.gpframework.module.module.domain.vo.UserStoreVo;
import com.gpframework.module.module.mapper.BrandAuditRecordMapper;
import com.gpframework.module.module.mapper.BrandInfoMapper;
import com.gpframework.module.module.service.IBrandAuditRecordService;
import com.gpframework.module.module.service.IBrandInfoService;
import com.gpframework.module.pay.utils.joinpay.sdk.utitls.StringUtil;
import com.gpframework.module.system.mapper.SysUserMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.File;
import java.net.URLEncoder;
import java.util.List;
import java.util.Set;

/**
 * @ClassName BrandInfo
 * @Author gpframework
 * @Date 2022-03-23
 * @Version 1.0.0
 * @Description 品牌信息Service业务层处理
 */
@Service
public class BrandInfoServiceImpl extends ServiceImpl<BrandInfoMapper, BrandInfo> implements IBrandInfoService {

    private static Logger logger = LoggerFactory.getLogger(AjaxResult.class);

    /**
     * 品牌审核持久层接口
     */
    @Autowired
    private BrandAuditRecordMapper brandAuditRecordMapper;

    /**
     * 品牌审核Service接口
     */
    @Autowired
    private IBrandAuditRecordService iBrandAuditRecordService;

    @Autowired
    private ICommonResourceService commonResourceService;

    /**
     * 系统用户持久层接口
     */
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private CommonWxUserMapper commonWxUserMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ICommonWxAppletInfoService commonWxAppletInfoService;

    @Override
    public CommonResourceVo getBrandLogo(Long brandId) {
        if (brandId == null) {
            return null;
        }

        CommonResourceReq resourceReq = new CommonResourceReq();
        resourceReq.setBrandId(brandId);
        resourceReq.setBusinessType(ResourcesBusiness.BRAND_COMPANY_LOGO.toString());
        QueryWrapper<CommonResource> lqw = new QueryWrapper<>();
        resourceReq.generatorQuery(lqw, true);
        List<CommonResourceVo> commonResourceVos = commonResourceService.listVo(lqw);

        return CollectionUtils.isEmpty(commonResourceVos) ? null : commonResourceVos.get(0);
    }

    /**
     * @Description 查询列表返回VO 用于返回给前端的列表接口
     * @Author gpframework
     * @Date 2022-03-23
     * @Param [lqw]
     * @Return List<BrandInfoVo>
     */
    @Override
    public List<BrandInfoVo> listVo(QueryWrapper<BrandInfo> lqw) {
        return this.baseMapper.listVo(lqw);
    }

    /**
     * @Description 通过查询详情VO 用于返回给前端的列详情接口
     * @Author gpframework
     * @Date 2022-03-23
     * @Param [id]
     * @Return BrandInfoVo
     */
    @Override
    public BrandInfoVo getVoById(Long id) {
        return this.baseMapper.getVo(id);
    }

    /**
     * 注册品牌
     *
     * @param brandInfo
     * @return
     */
    @Override
    @Transactional
    public boolean registered(BrandInfo brandInfo) {
        //是否注册成功
        Boolean success = false;
        brandInfo.setAuditStatus(1);
        brandInfo.setBrandNo(getBrandNo());
        //添加品牌
        int i = this.baseMapper.insert(brandInfo);
        // 添加品牌信息
        CommonWxUser commonWxUser = new CommonWxUser(brandInfo);
        commonWxUserMapper.insert(commonWxUser);
        if (i > 0) {
            //审核信息
            BrandAuditRecord brandAuditRecord = new BrandAuditRecord(brandInfo);
            brandAuditRecordMapper.insert(brandAuditRecord);
            success = true;
        }
        return success;
    }

    /**
     * 生成品牌编号
     *
     * @return
     */
    @Override
    public String getBrandNo() {
        String brandNo = "vk" + RandomUtil.randomNumbers(8);
        Integer i = this.baseMapper.findByBrandNo(brandNo);
        if (i > 0) {
            brandNo = getBrandNo();
        }
        return brandNo;
    }

    /**
     * 根据手机号码查询品牌信息
     *
     * @param mobile
     * @return
     */
    @Override
    public BrandInfoVo findByMobile(String mobile) {
        return this.baseMapper.findByMobile(mobile);
    }

    /**
     * 运营添加品牌
     *
     * @param brandInfo
     * @return
     */
    @Override
    @Transactional
    public Boolean add(BrandInfo brandInfo) {
        baseMapper.insert(brandInfo);
        if (brandInfo.getBrandId() == null) {
            return false;
        }
        brandInfo.setAuditStatus(BrandConstants.AUDIT_SUCCESS);
        BrandAuditRecord brandAuditRecord = new BrandAuditRecord(brandInfo);
        brandAuditRecord.setStatus(BrandConstants.AUDIT);
        iBrandAuditRecordService.save(brandAuditRecord);
        brandAuditRecord.setStatus(BrandConstants.AUDIT_SUCCESS);
        iBrandAuditRecordService.edit(brandAuditRecord);
        return true;
    }

    /**
     * 修改品牌信息
     *
     * @param brandInfoUpdate
     * @return
     */
    @Override
    @Transactional
    public boolean edit(BrandInfoUpdate brandInfoUpdate) {
        //品牌信息
        BrandInfo brandInfo = Convert.convert(new TypeReference<BrandInfo>() {
        }, brandInfoUpdate);
        String oldUserName = brandInfo.getUserName();
        brandInfo.setUserName(brandInfoUpdate.getMobile());
//        this.baseMapper.updateById(brandInfo);
        this.updateBrandInfoById(brandInfo);
        //修改密码
        if (!StringUtils.isEmpty(brandInfoUpdate.getPassword())) {
            SysUser sysUser = sysUserMapper.selectUserByUserName(brandInfo.getUserName());
            if (StringUtils.isEmpty(sysUser)) {
                throw new DataNotFoundException("对不起，当前账号不存在：" + brandInfo.getUserName());
            }
            sysUser.setPassword(brandInfoUpdate.getPassword());
            sysUser.setShowPassword(brandInfoUpdate.getShowPassword());
            sysUserMapper.updateUser(sysUser);
        }
        //登录账号
        SysUser sysUser = sysUserMapper.findByUserName(brandInfo.getUserName(), brandInfo.getBrandId());
        if (!StringUtils.isEmpty(sysUser) && !sysUser.getBrandUserId().equals(brandInfoUpdate.getBrandUserId())) {
            throw new BaseException("当前手机号已被使用");
        }
        if (StringUtils.isEmpty(sysUser)) {
            sysUser = sysUserMapper.selectUserById(brandInfo.getBrandUserId());
        }
        sysUser.setUserName(brandInfo.getMobile());
        sysUser.setPhonenumber(brandInfo.getMobile());
        sysUser.setNickName(brandInfo.getLeaderName());
        sysUserMapper.updateUser(sysUser);
        //用户信息
        CommonWxUser commonWxUser = commonWxUserMapper.getUserByBrandUserId(brandInfo.getBrandUserId());
        if (StringUtil.isNotEmpty(commonWxUser)) {
            commonWxUser.setUserName(brandInfo.getLeaderName());
            commonWxUser.setPhone(brandInfo.getMobile());
            commonWxUserMapper.updateById(commonWxUser);
        }
        return true;
    }

    @Override
    public boolean updateLogoAndSeal(BrandInfo brandInfo) {
        //品牌信息
        String key = CacheConstants.CACHE_BRAND_INFO + brandInfo.getBrandId();
        //删除缓存
        redisCache.deleteObject(key);
        return this.baseMapper.updateLogoAndSeal(brandInfo);
    }

    /**
     * 获取用户品牌账号列表
     *
     * @param brandStoreReq
     * @return
     */
    @Override
    public List<UserStoreVo> getUserBrandList(BrandStoreReq brandStoreReq) {
        return this.baseMapper.getUserBrandList(brandStoreReq);
    }

    /**
     * 获取品牌信息（缓存）
     *
     * @param brandId
     * @return
     */
    @Override
    public BrandInfoVo getBrandInfo(Long brandId) {
        //品牌信息
        String key = CacheConstants.CACHE_BRAND_INFO + brandId;
        //缓存获取品牌信息
        BrandInfoVo brandInfoVo = redisCache.getCacheObject(key);
        //没有缓存
        if (StringUtils.isEmpty(brandInfoVo)) {
            //删除缓存
            redisCache.deleteObject(key);
            //品牌信息
            brandInfoVo = this.baseMapper.getVo(brandId);
            //设置缓存
            redisCache.setCacheObject(key, brandInfoVo);
            //设置过期时间
            redisCache.expire(key, CacheConstants.CACHE_OVERDUE_AN_HOUR);
        }
        return brandInfoVo;
    }

    @Override
    public int updateBrandInfoById(BrandInfo brandInfo) {
        //品牌信息
        String key = CacheConstants.CACHE_BRAND_INFO + brandInfo.getBrandId();
        //删除缓存
        redisCache.deleteObject(key);
        return this.baseMapper.updateById(brandInfo);
    }

    /**
     * 设置品牌用户登录状态
     *
     * @param sysUser
     * @return
     */
    @Override
    public boolean updateBrandLoginStatus(SysUser sysUser) {
        sysUserMapper.updateBrandLoginStatus(sysUser);
        return true;
    }

    /**
     * 设置门店用户登录状态
     *
     * @param sysUser
     * @return
     */
    @Override
    public boolean updateStoreLoginStatus(SysUser sysUser) {
        this.sysUserMapper.updateStoreLoginStatus(sysUser);
        return true;
    }




}
